#!/bin/bash
# ==========================================================
# Oracle 11g Active Data Guard 全自动建置脚本
# 主机: 主库 10.255.18.9, 备库 10.255.20.22
# SID: interlib
# 数据目录: /home/oracle/oradata/interlib
# ==========================================================

# ---------- 用户检查 ----------
if [ "$(whoami)" != "oracle" ]; then
  echo "请用 oracle 用户执行此脚本！" | tee -a /tmp/adg_setup.log
  exit 1
fi

# ---------- 环境变量 ----------
export ORACLE_SID=interlib
# 主库 ORACLE_HOME
PRIMARY_ORACLE_HOME=/home/oracle/product/11.2.0
# 备库 ORACLE_HOME
STANDBY_ORACLE_HOME=/home/oracle/app/oracle/product/11.2.0/dbhome_1

HOSTNAME=$(hostname)
if [ "$HOSTNAME" == "primary" ]; then
  export ORACLE_HOME=$PRIMARY_ORACLE_HOME
  ROLE="primary"
elif [ "$HOSTNAME" == "standby" ]; then
  export ORACLE_HOME=$STANDBY_ORACLE_HOME
  ROLE="standby"
else
  echo "主机名未识别，请确保主机名为 primary 或 standby！" | tee -a /tmp/adg_setup.log
  exit 1
fi
export PATH=$ORACLE_HOME/bin:$PATH
LOGFILE=/home/oracle/adg_setup.log
exec > >(tee -a $LOGFILE) 2>&1

echo "==== 开始执行 ADG 配置 $(date) ===="
echo "当前角色: $ROLE, ORACLE_HOME: $ORACLE_HOME"

# ---------- 检查监听 ----------
echo "检查监听状态..."
lsnrctl status | grep "LISTENER"
if [ $? -ne 0 ]; then
  echo "监听未正常启动，请检查！"
  exit 2
fi

# ---------- 生成网络配置 ----------
echo "生成 listener.ora 与 tnsnames.ora ..."
NETWORK_DIR=$ORACLE_HOME/network/admin

# 自动备份原有配置文件
if [ -f "$NETWORK_DIR/listener.ora" ]; then
  cp $NETWORK_DIR/listener.ora $NETWORK_DIR/listener.ora.bak_$(date +%Y%m%d%H%M%S)
  echo "已备份 listener.ora 到 listener.ora.bak_$(date +%Y%m%d%H%M%S)"
fi
if [ -f "$NETWORK_DIR/tnsnames.ora" ]; then
  cp $NETWORK_DIR/tnsnames.ora $NETWORK_DIR/tnsnames.ora.bak_$(date +%Y%m%d%H%M%S)
  echo "已备份 tnsnames.ora 到 tnsnames.ora.bak_$(date +%Y%m%d%H%M%S)"
fi

cat > $NETWORK_DIR/listener.ora <<EOF
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = $(hostname -I | awk '{print $1}'))(PORT = 1521))
    )
  )

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (GLOBAL_DBNAME = interlibpri)
      (ORACLE_HOME = $PRIMARY_ORACLE_HOME)
      (SID_NAME = interlib)
    )
  )
EOF

cat > $NETWORK_DIR/tnsnames.ora <<EOF
interlibpri =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 10.255.18.9)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = interlibpri)
    )
  )

interlibstd =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = 10.255.20.22)(PORT = 1521))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = interlibstd)
    )
  )
EOF

echo "重新加载监听..."
lsnrctl reload
sleep 2

# ---------- 执行数据库参数配置 ----------
echo "执行 SQL 参数配置 ..."
sqlplus / as sysdba <<EOF
@/tmp/adg_config.sql
EOF
if [ $? -ne 0 ]; then
  echo "SQL 参数配置失败，请检查 adg_config.sql！"
  exit 3
fi

# ---------- 生成 Standby Redo Log ----------
echo "自动检测 redo log 数量并添加 Standby Redo Log ..."
REDO_COUNT=$(sqlplus -S / as sysdba <<EOF
set heading off feedback off
select count(*) from v\$log;
exit;
EOF
)
REDO_COUNT=$(echo $REDO_COUNT | grep -Eo '[0-9]+')
if [ -z "$REDO_COUNT" ]; then
  REDO_COUNT=4
fi
for i in $(seq 1 $REDO_COUNT); do
  sqlplus / as sysdba <<EOF
ALTER DATABASE ADD STANDBY LOGFILE THREAD 1
('/home/oracle/oradata/interlib/stdby0${i}.log') SIZE 200M;
EOF
  if [ $? -ne 0 ]; then
    echo "添加 Standby Redo Log stdby0${i}.log 失败！"
    exit 4
  fi
done

echo "所有 Standby Redo Log 添加完成。"

# ---------- 自动生成 RMAN 命令脚本 ----------
RMAN_SCRIPT=/home/oracle/rman_standby_setup.txt
cat > $RMAN_SCRIPT <<EOF
rman target sys@interlibpri auxiliary sys@interlibstd
DUPLICATE TARGET DATABASE FOR STANDBY FROM ACTIVE DATABASE
  DORECOVER
  SPFILE
  SET DB_UNIQUE_NAME='interlibstd'
  SET CONTROL_FILES='/home/oracle/oradata/interlib/control01.ctl'
  NOFILENAMECHECK;
EOF

echo "============================="
echo "请在备库执行以下 RMAN 命令（已生成 $RMAN_SCRIPT）："
cat $RMAN_SCRIPT
echo "============================="

echo "==== ADG 基础配置完成 $(date) ===="
